import Vue from 'vue'
import VueRouter from 'vue-router'

// 在app.vue中用router-view占位
// 在js代码中@会被解析成src的绝对路径
import Login from '@/views/Login/Login.vue'
import Reg from '@/views/Reg/Reg.vue'
import NotFound from '@/views/NotFound/NotFound.vue'
import Main from '@/views/Main/Main.vue'
import store from '@/store/index'
import Home from '@/views/menus/Home/Home.vue'
import UserInfo from '@/views/menus/User/UserInfo.vue'
import UserAvatar from '@/views/menus/User/UserAvatar.vue'
import UserPwd from '@/views/menus/User/UserPwd.vue'
import ArtCate from '@/views/menus/Article/ArtCate.vue'
import ArtList from '@/views/menus/Article/ArtList.vue'

Vue.use(VueRouter)
// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}
const routes = [
  // 一个对象表示一条路由规则
  // 此处用需要判断用户是否登录再跳
  {
    path: '/',
    name: 'Main',
    component: Main,
    redirect: '/home',
    children: [{ path: 'home', name: 'Home', component: Home },
      { path: 'user-info', name: 'UserInfo', component: UserInfo },
      { path: 'user-avatar', name: 'UserAvatar', component: UserAvatar },
      { path: 'user-pwd', name: 'UserPwd', component: UserPwd },
      { path: 'art-cate', name: 'ArtCate', component: ArtCate },
      { path: 'art-list', name: 'ArtList', component: ArtList }
    ]
  },
  { path: '/login', name: 'Login', component: Login },
  { path: '/reg', name: 'Reg', component: Reg },
  { path: '*', component: NotFound }
]

const router = new VueRouter({
  routes
})
// 导航守卫:路由器之间进行拦截
// to到哪去 from从哪来 next是否放行
router.beforeEach((to, from, next) => {
  // if (to.path === '/' && !store.state.token) {
  //   Vue.prototype.$message({ type: 'error', message: '请先登录' })
  //   next('/login')
  // }
  // next()
  const whiteList = ['/login', '/reg']
  // includes: 判断元素是否在数组内, 仅支持基本数据类型
  if (!whiteList.includes(to.path) && !store.state.token) {
  // if (!(to.path in whiteList) && !store.state.token) {
    Vue.prototype.$message.error('please上号谢谢')
    // next() 函数一旦执行就不会执行下一个 next 函数了
    next('/login')
  }
  next()
})
export default router
